package testpluginfile.popup.actions;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

import testpluginfile.popup.utils.EclipseUtils;

public class ConverterAction implements IObjectActionDelegate {

	private Shell shell;
	
	/**
	 * Constructor for Action1.
	 */
	public ConverterAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	*/
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	*/
	public void run(IAction action) {
		String path ="";				
        IFile ifileSrc = EclipseUtils.getFileSelected();		        
        if (ifileSrc != null) {
        	IProject project = ifileSrc.getProject();		        	
        	path = ifileSrc.getRawLocation().toOSString();
        	File fileSrc = new File(path) ;					
			String r = ConverterROT13.convertFile(fileSrc);
			String nameOutput = path + ".rot13.txt" ; 
			File outputFile = new File(nameOutput) ;
			try {
				Writer w = new FileWriter(outputFile) ;
				w.write(r);
				w.close();
				System.out.println("fichier " + nameOutput + " du projet " + project.getName() + " créé/ecrase") ;
				EclipseUtils.refreshFile(outputFile,ifileSrc.getParent(),project );
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
        	System.out.println("Err fichier introuvable" ) ;
        }		        		        
	}

	

	
	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}

}
